/**
 * $Id: RegisterController.java 19 2011-06-11 04:06:06Z feigme $
 */
package com.iary.interfaces.web.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iary.application.UserServiceFacade;
import com.iary.domain.model.user.UserExistedException;

@Controller
public class RegisterController {

	@Autowired
	private UserServiceFacade userServiceFacade;

	@Autowired
	private RegisterCommandValidator validator;

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String execute(@ModelAttribute("command") RegisterCommand command,
			BindingResult errors) {
		return "user/register";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(@ModelAttribute("command") RegisterCommand command,
			BindingResult errors) {
		validator.validate(command, errors);
		if (!errors.hasErrors()) {
			try {
				userServiceFacade.register(command.getEmail(), command
						.getUserName(), command.getPassword());
			} catch (UserExistedException e) {
				return "user/register";
			}
		}
		return "user/register";
	}

}
